package com.yc.bbs.controller;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.yc.bbs.dao.BoardMapper;
import com.yc.bbs.entity.Board;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.Jedis;

import java.util.List;

/**
 * <p>
 * BBS论坛-板块表-13 前端控制器
 * </p>
 *
 * @author ly
 * @since 2024-11-23
 */
@RestController
@RequestMapping("/board")
public class BoardController {
    @Autowired
    BoardMapper boardMapper;

    ObjectMapper objectMapper = new ObjectMapper();
    @GetMapping("query")
    Object query() throws JsonProcessingException {
        try(Jedis jedis = new Jedis("127.0.0.1",7000);){
            // 默认访问本机6379
            String key = "bbs_home_boards";
            if (jedis.exists(key)) {
                System.out.println("读取redis缓存数据OK");
                String json = jedis.get(key);
                List list = objectMapper.readValue(json, List.class);
                return list;
            } else {
                System.out.println("存储redis缓存数据OK");
                List<Board> boards = boardMapper.selectByPid(0);
                String json = objectMapper.writeValueAsString(boards);
                jedis.set(key, json);
                return boards;
            }
        }
    }
    @RequestMapping("queryById")
    Board queryById(int id){
        return boardMapper.selectById(id);
    }

}
